package com.alennus.blog.nio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Created by pactera on 2018/9/26.
 */
public class NioTest {


    public static void main(String[] args){
        /**
         * transferFrom()
         *  FileChannel的transferFrom()方法可以将数据从源通道传输到FileChannel中
         */

        String fileAddress = "D:\\logs\\spring-boot-logging.log";
        String toFileAddress = "D:\\logs\\spring.log";
        String toAddress = "D:\\logs\\spring2.log";
        Path path1 = Paths.get(fileAddress);

        try {
            RandomAccessFile fromFile  = new RandomAccessFile(path1.toFile(),"rw");
            FileChannel fromChannel  = fromFile.getChannel();


            File file = new File(toAddress);
            if(!file.exists()){
                file.createNewFile();
            }

            RandomAccessFile toFile  = new RandomAccessFile(toFileAddress,"rw");
            FileChannel toChannel  = toFile.getChannel();

            RandomAccessFile toFile2  = new RandomAccessFile(toAddress,"rw");
            FileChannel toChannel2  = toFile2.getChannel();

            long position = 0;
            long count = fromChannel.size();

            toChannel.transferFrom(fromChannel,position,count);
            fromChannel.transferTo(position,count,toChannel2);
            fromChannel.close();
            toChannel.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
